import React, { useState, useEffect } from 'react';
import { Modal, Button, Skeleton, Image, message, Upload, Row, Col, Space, Input, Typography, Divider, List } from 'antd'
import { UploadOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import {
  ProFormText,
  ProForm,
  ProFormDatePicker,
  ProFormDateTimePicker,
  ProFormSelect,
  ProFormTextArea,
  ProFormUploadButton,
  ProFormCascader,
  ProFormRadio
} from '@ant-design/pro-components';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';
import type { EditModalProps } from '../data';

// import { reqAddActAnswer, reqUpdateActAnswer } from '@/services/firstConsultation';

import {
  addCreatePatient,
  addUpdatePatient,
  getPatientDetail,
  getOrganizeList,
  getOrganizeCreate,
  getOrganizeUpdate,
  reqRrderCreate,
  reqRrderUpdate,
  reqRrderDetail,
  reqOrderDetail,
  reqAllDetail,
  reqAllDetailWithType
} from '@/services/register';


const PayTypeEditModal: React.FC<EditModalProps> = ({ row, isOpen, handleModal, actionRef }) => {
  const title = row?.id ? "支付" : "创建团体账号"
  const [formObj] = ProForm.useForm()
  const [initialValues, setinitialValues] = useState<any>(null)
  const [detailInfo, setDetailInfo] = useState<any>();
  // const [yuer, setYuer] = useState<any>(0);
  const [yaoItem, setYaoItem] = useState<any>();

  const handleAdd = async (params: any) => {
    const res = await getOrganizeCreate({ ...params })
    if (res?.resultCode === "00000000") {
      message.success(res?.message)
      handleModal(true)
    } else {
      message.error(res?.message)
    }
  }

  const handleEditor = async (params: any) => {
    const res = await reqRrderUpdate({
      ...params,
      id: row?.id,
      discountPrice: row?.discountPrice,
      originalPrice: row?.originalPrice,
      status: 2,
    })
    if (res?.resultCode === "00000000") {
      message.success('支付成功')
      // actionRef?.current.reload()
      handleModal(true)
    } else {
      message.error(res?.message)
    }
  }

  function listItemMeta(medicineName:string, money:any, quantity:any){
    return <>{medicineName}(￥{money})<span style={{padding:'0 20px'}}>x&nbsp;{quantity}</span></>
  }

  const handleDataChange = (value: any) => {
    let payType = formObj.getFieldValue('payType');
    let originalPrice = row?.originalPrice;
    let yuer = formObj.getFieldValue('balancePayAmount');
    if (!yuer) yuer = 0;
    if (payType == '6') {
      yuer = originalPrice;
      formObj.setFieldValue('balancePayAmount', originalPrice);
    }
    let money = parseInt(originalPrice) - parseInt(yuer);
    // formObj.setFieldValue('money', money)
  }

  const handleOrderPay = async (id: any) => {
    const res = await reqAllDetailWithType({ id: id },2);
    let info: JSX.Element[] = [];
    if (res?.resultCode === "00000000") {
      setYaoItem(res?.data?.orderDetail);

       debugger
      // res?.data?.orderDetail?.map((item: any) => {
      //   if (item?.medicineType == 1) {
      //     info.push(<><Typography.Text>【中药材】</Typography.Text><br /></>);
      //     for (let j = 0; j < item?.orderItemList?.length; j++) {
      //       let tmp = `${item?.orderItemList[j]?.medicineName}  x ${item?.orderItemList[j]?.quantity}`;
      //       info.push(<><Typography.Text>{tmp}</Typography.Text><br /></>);
      //     }
      //   } else if (item?.medicineType == 2) {
      //     info.push(<><Typography.Text>【西药】</Typography.Text><br /></>);
      //     for (let j = 0; j < item?.orderItemList?.length; j++) {
      //       let tmp = `${item?.orderItemList[j]?.medicineName}  x ${item?.orderItemList[j]?.quantity}`;
      //       info.push(<><Typography.Text>{tmp}</Typography.Text><br /></>);
      //     }
      //   } else if (item?.medicineType == 3) {
      //     info.push(<><Typography.Text>【针灸】</Typography.Text><br /></>);
      //     for (let j = 0; j < item?.orderItemList?.length; j++) {
      //       let tmp = `${item?.orderItemList[j]?.medicineName}  x ${item?.orderItemList[j]?.quantity}`;
      //       info.push(<><Typography.Text>{tmp}</Typography.Text><br /></>);
      //     }
      //   }

      // });
      //setDetailInfo(info);
    } else {
      message.error(res?.message)
    }
  }

  useEffect(() => {
    if (row?.id) {
      let { id, phoneNumber, answerData, actId, payType, projectName, money, originalPrice } = row
      formObj.setFieldValue('yuer', 0);
      setinitialValues({
        id, phoneNumber, answerData, actId, projectName, money, originalPrice, receiveMethod: payType?.toString() ?? '1'
      })

      handleOrderPay(id);
    }

    //handleActIdData({});

  }, [])




  return (
    <Modal width={800} title={title} open={isOpen} onCancel={() => handleModal(false)} footer={null} destroyOnClose={true}>
      {
        initialValues === null && row?.id ? <Skeleton active paragraph={{ rows: 6 }} /> :
          <ProForm
            form={formObj}
            initialValues={initialValues}
            onChange={handleDataChange}
            onFinish={(values): Promise<any> => row?.id ? handleEditor(values) : handleAdd(values)}>
            <Row gutter={24}>
              <Col span={16}>
                <Space size={24}>
                  <Typography.Text>{row?.projectName == 1 ? '挂号费' : '医药费'}</Typography.Text>
                  <Typography.Title level={3} style={{ color: 'red' }}>￥{row?.originalPrice}</Typography.Title>
                </Space>
              </Col>
              <Col span={8} style={{ position: 'absolute', right: 30, height: 260, width:225, overflowY:'auto' }}>
                {/* {detailInfo} */}
                {yaoItem ?
                  yaoItem?.map((item:any)=>{
                    return <List itemLayout="horizontal" dataSource={item.orderItemList}
                      renderItem={(it, index) => (
                        <List.Item style={{borderBottom:"2px dotted rgb(228, 228, 228)",fontSize:12}}>
                          {listItemMeta(it?.medicineName, it?.money, it?.quantity)}
                        </List.Item>
                      )}
                    />
                  })
                : null}
              </Col>

              <Col span={16}>
                <Space size={24}>
                  <ProFormText name='balancePayAmount' label="余额" placeholder='请输入要使用余额的金额' />
                  <ProFormText name='money' disabled label="还需支付" />
                </Space>
              </Col>

              <Col span={16}>
                <ProFormRadio.Group
                  name="payType"
                  label="支付方式"
                  // fieldProps={{
                  //   defaultValue: '1'
                  // }}
                  rules={[
                    {
                      required: true,
                      message: '请选择支付方式'
                    }
                  ]}
                  // [1:微信,2:支付宝,3:银行卡,4:现金,5:医保]
                  options={[
                    {
                      label: '微信',
                      value: '1',
                    },
                    {
                      label: '支付宝',
                      value: '2',
                    },
                    {
                      label: '银行卡',
                      value: '3',
                    },
                    {
                      label: '现金',
                      value: '4',
                    },
                    {
                      label: '医保',
                      value: '5',
                    },
                    {
                      label: '余额',
                      value: '6',
                    },
                    {
                      label: '赊账',
                      value: '7',
                    }
                  ]}
                />
              </Col>
            </Row>
          </ProForm>
      }
    </Modal >
  );
};
export { PayTypeEditModal }


